#include "EnemyManager.h"
#include "Enemy.h"
#include "CsvUtil.h"
#include "Tank.h"

EnemyManager::EnemyManager(){

}

EnemyManager::~EnemyManager(){

}

EnemyManager* EnemyManager::createWithLevel(int level){
	auto manager = new EnemyManager();
	if (manager && manager->initWithLevel(level)){
		manager->autorelease();
	}
	else{
		CC_SAFE_DELETE(manager);
	}
	return manager;
}

bool EnemyManager::initWithLevel(int level){
	bool bRet = false;
	do
	{
		CsvUtil::getInstance()->loadFile(StringUtils::format("Tollgate/Level_%d.csv", level).c_str());
		int n = CsvUtil::getInstance()->getFileRowColNum(StringUtils::format("Tollgate/Level_%d.csv", level).c_str()).width;
		CCLOG("Level = %d", level);
		CCLOG("EnemyNum = %d", n);
		m_num = n - 2;
		for (int i = 1; i < n - 1; i++){
			auto num = CsvUtil::getInstance()->getInt(i, 1, StringUtils::format("Tollgate/Level_%d.csv", level).c_str());
			auto hp = CsvUtil::getInstance()->getInt(i, 2, StringUtils::format("Tollgate/Level_%d.csv", level).c_str());
			auto atk = CsvUtil::getInstance()->getInt(i, 3, StringUtils::format("Tollgate/Level_%d.csv", level).c_str());
			auto speed = CsvUtil::getInstance()->getInt(i, 4, StringUtils::format("Tollgate/Level_%d.csv", level).c_str());
			auto bullet = CsvUtil::getInstance()->getInt(i, 5, StringUtils::format("Tollgate/Level_%d.csv", level).c_str());

			auto enemy = Enemy::create(Tank::createWithNum(num));
			enemy->setHP(hp);
			enemy->setAtk(atk);
			enemy->setSpeed(speed);
			enemy->setBullet(bullet);

			m_enemyList.pushBack(enemy);
			this->addChild(enemy);

			EnemyController* controller = EnemyController::create();
			enemy->setController(controller);
			controller->setControllerListener(enemy);
			this->addChild(controller);
		}
		bRet = true;
	} while (0);
	return bRet;
}

void EnemyManager::setTiledMap(TMXTiledMap* map){
	int i = 0;
	for (auto enemy : m_enemyList){
		i++;
		enemy->setTiledMap(map);
		TMXObjectGroup* objGroup = map->getObjectGroup("objects");

		ValueMap playerPointMap = objGroup->getObject(StringUtils::format("EnemyPoint%d", i));
		float X = playerPointMap.at("x").asFloat();
		float Y = playerPointMap.at("y").asFloat();
		enemy->setPosition(Vec2(X, Y));
	}
}

Vector<Enemy*> EnemyManager::getEnemyList(){
	return m_enemyList;
}

void EnemyManager::delNum(){
	m_num--;
	if (m_num == 0){
		NotificationCenter::getInstance()->postNotification("win", NULL);
	}
}
